package com.example.springboot.controller;

import com.example.springboot.entity.LoginRequest;
import com.example.springboot.entity.User;
import com.example.springboot.service.UserService;
import com.example.springboot.utils.JwtUtils;
import com.example.springboot.utils.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtils jwtUtils;

    @PostMapping("/login")
    public ResponseResult<LoginResponse> login(@RequestBody LoginRequest loginRequest) {
        try {
            // 1. 调用服务层验证用户名密码
            User user = userService.login(loginRequest.getUsername(), loginRequest.getPassword());

            // 2. 生成JWT令牌
            String token = jwtUtils.generateToken(user.getUsername());

            // 3. 返回用户信息和令牌
            return ResponseResult.success(new LoginResponse(user, token));
//            return ResponseResult.success("data");
        } catch (RuntimeException e) {
            // 4. 登录失败（用户名不存在或密码错误）
            return ResponseResult.fail(e.getMessage());
        }
    }

    // 内部类：登录成功响应数据
    static class LoginResponse {
        private User user;
        private String token;

        public LoginResponse(User user, String token) {
            this.user = user;
            this.token = token;
        }

        // getter/setter（Lombok的@Data也可，这里简化）
        public User getUser() { return user; }
        public String getToken() { return token; }
    }
}


